package chaoyue.study.jdbc;

import chaoyue.study.jdbc.utils.DbUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * 使用预编译的方式执行SQL
 * 为了简化书写，后续都暂时都不处理资源的释放，记得有这么一回事就行
 * PreparedStatement其实默认是不执行数据库端的预编译的，需要在数据库连接URL中添加参数useServerPrepStmts=true&cachePrepStmts=true进行开启
 * prepareStatement阶段对应数据库中的prepare阶段，executeQuery阶段对应数据库中的set和execute阶段
 */
public class Test3_PreparedStatement {
    public static void main(String[] args) throws Exception {
        Connection connection = DbUtils.getConnection();

        // SQL预编译，生成PrepareStatement对象
        PreparedStatement statement =
                connection.prepareStatement("select id,username,password,birthday from test_user where id = ?");
        // 参数填充
        statement.setInt(1, 2);
        // 执行SQL 查询结果集
        ResultSet resultSet = statement.executeQuery();
        while (resultSet.next()) {
            System.out.println("id=" + resultSet.getInt("id"));
            System.out.println("username=" + resultSet.getString("username"));
            System.out.println("password=" + resultSet.getString("password"));
            System.out.println("birthday=" + resultSet.getString("birthday"));
        }
    }
}